<template>
  <section>
    <div v-wechat-title="pageTitle" v-if="pageTitle"></div>

    <van-sticky>
      <PageHeader title="课程"/>
    </van-sticky>

    <template v-if="course">
      <img :src="course.img_url" class="w100" />
      <div class="bg-color-white pd10">
        <div class="text-left font-large strong">{{course.name}}</div>
        <div class="flex flex-row mt10 flex-centerV font-common color-gray-dark">
          <!-- <div class="flex flex-row flex-left flex-1">{{course.apply_amount}}人在学</div> -->
          <div class="flex flex-row flex-right flex-1" v-if="course.is_online==1">在线课程</div>
        </div>
        <div class="text-left font-common color-gray-dark mt10" v-if="course.is_online==0">上课地点：{{course.region}}</div>
      </div>

      <div class="text-left bg-color-white pd10 mt10 detail" v-html="course.detail"></div>

      <div class="empty-box"></div>

      <div class="flex flex-row flex-center bg-color-white bottom-wrapper">
        <div class="flex flex-col flex-centerH pl20 pr20 color-green item" @click="$router.push({path: '/'})">
          <div class="flex flex-row flex-center">
            <i class="iconfont icon-shouye"/>
          </div>
          <div class="flex flex-row flex-center font-common">
            首页
          </div>
        </div>

        <div class="flex flex-col flex-centerH pl20 pr20 color-green item" @click="shareGuideWrapperVisible=true">
          <div class="flex flex-row flex-center">
            <i class="iconfont icon-fenxiang"/>
          </div>
          <div class="flex flex-row flex-center font-common">
            分享
          </div>
        </div>

        <div class="flex flex-row flex-center flex-1 bg-color-gray item" v-if="joined">
          已报名
        </div>
        <div class="flex flex-row flex-center flex-1 bg-color-green color-white item" @click="chargeOverlayVisible=true" v-else>
          立即报名(<span v-if="course.charge>0">￥{{course.charge}}</span><span v-else>免费</span>)
        </div>

      </div>

      <div class="share-guide-wrapper" @click="shareGuideWrapperVisible=false" v-if="shareGuideWrapperVisible">
        <img :src="STATIC_BASE_URL + 'images/mp/share-guide.png'"/>
      </div>

      <van-overlay :show="chargeOverlayVisible">
        <div class="flex flex-col flex-center recharge-wrapper" style="height: 100%;">
          <div class="flex flex-col pd20 round-box bg-color-white recharge-box">
            <div class="flex flex-row flex-center strong font-biger">
              参加课程<span class="font-common color-gray-dark ml10">(<span
              class="color-red">{{course.charge}}</span>)金币</span>
            </div>

            <div class="flex flex-row flex-center mt20">
              <div class="flex flex-row flex-center pr10">
                <i class="iconfont icon-viphuiyuanhuangguan" style="font-size: 26px;color: #ff0000;"/>
              </div>

              <div class="flex flex-col flex-centerH flex-1">
                <div class="flex flex-row flex-left strong font-biger">VIP特权</div>
                <div class="flex flex-row flex-left color-gray font-common">免费参加课程</div>
              </div>

              <div class="flex flex-row flex-center pl10">
                <van-button type="warning" round size="small" @click="$router.push({name: 'VipBuy'})">马上升级</van-button>
              </div>
            </div>

            <div class="flex flex-row flex-center mt20">
              <div class="flex flex-row flex-center pr10">
                <i class="iconfont icon-taojinbi" style="font-size: 26px;color: #9266f9;"/>
              </div>

              <div class="flex flex-col flex-centerH flex-1">
                <div class="flex flex-row flex-left strong font-biger">金币支付</div>
                <div class="flex flex-row flex-left color-gray font-common">当前可用金币：<span class="color-green">{{user && user.gold_coin ? user.gold_coin : 0}}</span>
                </div>
              </div>

              <div class="flex flex-row flex-center pl10">
                <van-button type="warning"
                            round
                            size="small"
                            :disabled="user && user.gold_coin >= course.charge ? false : true"
                            @click="onCreateGoldCoinChargeOrder">立即参加
                </van-button>
              </div>
            </div>

            <div class="flex flex-row flex-center mt20">
              <div class="flex flex-row flex-center pr10">
                <i class="iconfont icon-weixinzhifu" style="font-size: 26px;color: #16c2c2;"/>
              </div>

              <div class="flex flex-col flex-centerH flex-1">
                <div class="flex flex-row flex-left strong font-biger">在线支付</div>
                <div class="flex flex-row flex-left color-gray font-common">掌握婚姻的奥秘</div>
              </div>

              <div class="flex flex-row flex-center pl10">
                <van-button type="warning" round size="small" @click="onCreateChargeOrder">立即支付</van-button>
              </div>
            </div>

          </div>

          <div class="flex flex-row flex-center pd20">
            <i class="iconfont icon-guanbi" style="font-size: 34px; color: #FFFFFF;"
               @click="chargeOverlayVisible=false"/>
          </div>
        </div>
      </van-overlay>

      <van-overlay :show="sharePosterPopupVisible">
        <div class="flex flex-col flex-center" style="height: 100%;">
          <div class="flex flex-col pd10 bg-color-white round-box" style="width: 60%;">
            <div class="flex flex-row flex-center">
              <img :src="sharePosterImg" class="w100" v-if="sharePosterImg" />
              <van-empty
                class="custom-image"
                :image="STATIC_BASE_URL + 'images/mp/loading.gif'"
                v-else
              />
            </div>
            <div class="flex flex-row flex-center text-center mt5 font-common">长按图片发给好友或保存到本地后发到朋友圈</div>
          </div>

          <div class="flex flex-row flex-center pd10">
            <i class="iconfont icon-guanbi" style="font-size: 34px; color: #FFFFFF;" @click="sharePosterPopupVisible=false" />
          </div>
        </div>
      </van-overlay>

      <div class="flex flex-col flex-center sidebar-card" @click="showSharePosterPopup">
        <div class="flex flex-row flex-center">
          <i class="iconfont icon-qiapian" />
        </div>
        <div class="flex flex-row flex-center font-small">邀请卡</div>
      </div>
    </template>
  </section>
</template>

<script>
  import Vue from 'vue';
  import {Toast, Dialog, Sticky, Button, Overlay} from 'vant';
  import {
    activitySharePosterUri,
    courseInfoUri, courseOrderCreateUri, courseSharePosterUri,
    serviceChargeOrderCreateUri,
    STATIC_BASE_URL,
    wechatJsApiConfigUri, wxPayCreateCourseOrderPayTradeUri, wxPayQueryUri, wxPayServiceChargeOrderPayTradeUri
  } from "../../common/api";
  import PageHeader from "../componets/PageHeader";
  import {
    IID_TYPE_ACTIVITY,
  } from "../../common/constants";
  import util from "../../assets/js/util";

  Vue.use(Toast).use(Dialog).use(Sticky).use(Button).use(Overlay);

  export default {
    components: {
      PageHeader
    },
    data() {
      return {
        STATIC_BASE_URL: STATIC_BASE_URL,
        pageTitle: null,
        course: null,
        joined: false,
        shareGuideWrapperVisible: false,
        wxReady: false,
        chargeOverlayVisible: false,
        member: null,
        user: null,
        sharePosterPopupVisible: false,
        sharePosterImg: null
      }
    },
    methods: {
      getInfo() {
        const that = this;
        this.$http.get(courseInfoUri + '?id=' + this.$route.query.id).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            that.toast(msg);
          } else {
            data.course.charge = parseFloat(data.course.charge);
            that.course = data.course;
            that.joined = data.joined;
            that.pageTitle = data.course.name;
            that.updateShareData();
          }
        }, response => {
          // error callback
        })
      },
      getJsApiConfig() {
        if(!isWxServiceEnable) {
          return;
        }
        const that = this;
        const url = wechatJsApiConfigUri + '?url=' + encodeURIComponent(window.location.href);
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            that.toast(msg);
          } else {
            wx.config({
              debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
              appId: data.appId, // 必填，公众号的唯一标识
              timestamp: data.timestamp, // 必填，生成签名的时间戳
              nonceStr: data.nonceStr, // 必填，生成签名的随机串
              signature: data.signature,// 必填，签名
              jsApiList: ['onMenuShareAppMessage', 'onMenuShareTimeline', 'updateAppMessageShareData', 'updateTimelineShareData', 'hideOptionMenu', 'showOptionMenu', 'hideMenuItems', 'showMenuItems', 'chooseWXPay'] // 必填，需要使用的JS接口列表
            });

            wx.ready(function () {
              that.wxReady = true;
              console.log('wx配置成功');
              that.updateShareData();
            });

            wx.error(function (res) {
              console.log('wx配置出错');
            });
          }
        }, response => {
          // error callback
        })
      },
      updateShareData() {
        if (isWxServiceEnable && this.wxReady && this.course) {
          const title = this.course.name;
          const imgUrl = this.course.img_url;
          const link = window.location.href;
          const desc = this.course.intro;

          wx.updateAppMessageShareData({
            title: title, // 分享标题
            desc: desc, // 分享描述
            link: link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: imgUrl, // 分享图标
            success: function () {
              // 设置成功
              console.log('updateAppMessageShareData');
            }
          });

          wx.updateTimelineShareData({
            title: title, // 分享标题
            link: link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: imgUrl, // 分享图标
            success: function () {
              // 设置成功
              console.log('updateTimelineShareData');
            }
          })
        }
      },
      onCreateGoldCoinChargeOrder() {
        if (!this.GLOBAL.userInfo) {
          this.$router.push({name: 'UserLogin'});
          return;
        }
        const that = this;
        const fromuid = localStorage.getItem('fromuid') ? localStorage.getItem('fromuid') : 0;
        const url = courseOrderCreateUri + '?fromuid=' + fromuid + '&course_id=' + this.course.id + '&money_type=gold_coin';
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body;
          if (code != 0) {
            Toast(msg);
          } else {
            that.chargeOverlayVisible = false;
            Toast('购买成功');
            that.$router.push({name: 'MyCourseOrder', query: {sn: data.order_sn}});
          }
        }, response => {
          // error callback
        })
      },
      onCreateChargeOrder() {
        if (!this.GLOBAL.userInfo) {
          this.$router.push({name: 'UserLogin'});
          return;
        }
        const that = this;
        const fromuid = localStorage.getItem('fromuid') ? localStorage.getItem('fromuid') : 0;
        const url = courseOrderCreateUri + '?fromuid=' + fromuid + '&course_id=' + this.course.id + '&money_type=money';
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            Toast(msg);
          } else {
            that.chargeOverlayVisible = false;
            if(that.course.charge > 0) {
              that.chooseWXPay(data.order_sn);
            } else {
              Toast('购买成功');
            }
          }
        }, response => {
          // error callback
        })
      },
      chooseWXPay(orderSn) {
        const that = this;
        const url = wxPayCreateCourseOrderPayTradeUri + '?order_sn=' + orderSn;
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            that.toast(msg);
          } else {
            const payParams = JSON.parse(data.pay_params);
            wx.chooseWXPay({
              timestamp: payParams.timeStamp,
              nonceStr: payParams.nonceStr,
              package: payParams.package,
              signType: payParams.signType,
              paySign: payParams.paySign,
              success: function (res) {
                // 支付成功后的回调函数
                Toast('支付成功');
                that.onPaied(orderSn, data.pay_trade_no);
              },
              // 支付取消回调函数
              cancel: function (res) {
                Toast('用户取消支付~');
                that.$router.push({name: 'MyCourseOrder', query: {sn: orderSn}});
              },
              fail: function (res) {
                Toast('支付失败');
                that.$router.push({name: 'MyCourseOrder', query: {sn: orderSn}});
              }
            });
          }
        }, response => {
          // error callback
        });
      },
      onPaied(orderSn, payTradeNo) {
        const that = this;
        const url = wxPayQueryUri + '?pay_trade_no=' + payTradeNo;
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            that.toast(msg);
          } else {
            if (data.success == 1) {
              that.$router.push({name: 'MyCourseOrder', query: {sn: orderSn}});
            } else {
              that.toast('支付出错，请重试或联系客服付款');
            }
          }
        }, response => {
          // error callback
        })
      },
      showSharePosterPopup() {
        if(!this.GLOBAL.userInfo) {
          this.$router.push({name: 'UserLogin'});
          return;
        }
        this.sharePosterPopupVisible = true;
        const fromuid = this.GLOBAL.userInfo.id;
        const that = this;
        const url = courseSharePosterUri + '?course_id=' + this.$route.query.id + '&fromuid=' + fromuid;
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            that.toast(msg);
          } else {
            that.sharePosterImg = data.url;
          }
        }, response => {
          // error callback
        });
      }
    },
    created: function () {
      const fromuid = window.localStorage.getItem('user_id') ? window.localStorage.getItem('user_id') : 0;
      let _href = window.location.href;
      if (isWxServiceEnable && _href.indexOf('&replace=1') <= -1) {
        window.location.replace(_href + '&replace=1&fromuid=' + fromuid)
      } else if (_href.indexOf('fromuid=') > -1) {
        const fromuidVar = util.getQueryVariable('fromuid');
        if(fromuid > 0 && fromuid != fromuidVar) {
          window.location.replace(_href.replace('fromuid=' + fromuidVar, 'fromuid=' + fromuid));
        }
      }
    },
    mounted: function () {
      if (this.GLOBAL.userInfo) {
        this.user = this.GLOBAL.userInfo;
        this.user.gold_coin = parseFloat(this.user.gold_coin);
        this.member = this.GLOBAL.memberProfile;
      }
      this.EventBus.$on('OnUserLogined', () => {
        this.user = this.GLOBAL.userInfo;
        this.user.gold_coin = parseFloat(this.user.gold_coin);
        this.member = this.GLOBAL.memberProfile;
        this.getInfo();
      });

      this.getInfo();
      this.getJsApiConfig();
    }
  }
</script>

<style>
  .detail img {
    width:auto; 
    height:auto; 
    max-width:100%; 
    max-height:100%;
  }

  .empty-box {
    height: calc(50px + env(safe-area-inset-bottom));
  }

  .bottom-wrapper {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding-bottom: calc(10px + env(safe-area-inset-bottom));
  }

  .bottom-wrapper .item {
    height: 50px;
  }

  .bottom-wrapper .item .iconfont {
    font-size: 20px;
  }

  .sidebar-card {
    height: 60px;
    width: 60px;
    border-radius: 30px;
    top: 160px;
    right: 5px;
    position: fixed;
    background: #4843ff;
    color: #FFFFFF;
  }
  .sidebar-card .iconfont {
    font-size: 20px;
  }
  .custom-image .van-empty__image {
    width: 100px;
    height: 100px;
  }
</style>
